package com.manage.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.manage.dao.IBaseDao;
import com.manage.po.User;
import com.manage.service.IUserService;
import com.manage.util.PagerModel;



@Service("UserService")
@Transactional(propagation = Propagation.REQUIRED)
public class UserService implements IUserService{

	@Autowired
	private IBaseDao baseDao;
		
	@Override
	public User getUserById(String userid) {
	
		return baseDao.get(User.class, userid);
	}

	@Override
	public void merge(User user) {
		baseDao.merge(user);
	}

	@Override
	public PagerModel getUserById(String userid, int pageno, int pagesize) {

		
//		String hql="select distinct t.teamid,t.teamname,pm.membername,t.teacher_instruct,t.roomID,t.description" +
//				" from team t left join projectmember pm on t.teamid = pm.teamid";
		
		String sql = "select * from user";
		System.out.println("********" + sql);
		return baseDao.findPageBySql(User.class, sql, null, pageno, pagesize);
	}

	@Override
	public void save(User user) {
		
			baseDao.save(user);
	}

	@Override
	public void update(User user) {
		
		baseDao.update(user);
	}

	@Override
	public void delete(String userid) {
	
		User user = getUserById(userid);
		baseDao.delete(user);
	}

	@Override
	public void batchDelete(String[] ids) {
		
		for(int i=0;i<ids.length;i++)
			delete(ids[i]);	
	}
	
	@Override
	public PagerModel search(String userid, String username, 
			String cardid, int pageno, int pagesize) {
		List<Criterion> cronlist = new ArrayList<Criterion>();
		if(userid!=null && !userid.equals(""))
			cronlist.add(Restrictions.like("userid",userid,MatchMode.ANYWHERE));
		if(username!=null && !username.equals(""))
			cronlist.add(Restrictions.like("username",username,MatchMode.ANYWHERE));
		if(cardid!=null && !cardid.equals(""))
			cronlist.add(Restrictions.like("cardid",cardid,MatchMode.ANYWHERE));
		
		return baseDao.findPageByCriterion(User.class, pageno, pagesize, null, cronlist);
	}

	@Override
	public User TestHql(String userid) {
		
		String hql="from User where userid=?";//HQL语句中表名应该是ORM映射的类名,查询結果是实体类，而不是sql的结果集
		List<User> list=baseDao.findByHql(hql, userid);
		return list.get(0);
	}

	@Override
	public User TestHql(String... param) {
		String hql="from User where userid=?";
		List<User> list=baseDao.findByHql(hql, param);
		return list.get(0);
	}

}
